<template>
  <div class="home-view">
    <NavBar>
      <template #default> 首页 </template>
    </NavBar>
    <SearchBar />
    <BannerView :bannerData="banners" />
    <RecommendView :recommendData="recommends" />
    <TabControl :tabData="tabs" @tabClick="tabClick" />

    <div class="scroll-container" ref="scrollContainer">
      <GoodsList :goodsData="fetchedGoods" />
      <div v-if="loadingGoods" class="loading-indicator">加载中...</div>
      <div v-if="goodsError" class="error-message">
        {{ goodsError }}
      </div>
      <div v-if="noMoreData" class="no-more-data">没有更多了...</div>
    </div>
  </div>
</template>

<script setup>
import { watch, onMounted, ref, onUnmounted } from "vue";
import NavBar from "../../components/common/NavBar.vue";
import SearchBar from "../../components/common/SearchBar.vue";
import BannerView from "./BannerView.vue";
import RecommendView from "./RecommendView.vue";
import TabControl from "../../components/content/TabControl.vue";
import GoodsList from "../../components/content/GoodsList.vue";

import { getAllBannerList } from "@/api/BannerApi";
import { getAllCategoryList } from "@/api/CategoryApi";
import { getAllDealProductList } from "@/api/ProductApi";
import { useShopStore } from "@/stores/shop";

// --- State Variables ---
const shopStore = useShopStore();

const banners = ref([]);
const recommends = ref([]);
const tabs = ref([]);

const currentType = ref("deal");
const currentPage = ref(1); // Track the current page number
const pageSize = 3; // Number of items per page (adjust as needed)

const loadingGoods = ref(false); // 商品加载状态
const goodsError = ref(null); // 商品加载错误
const fetchedGoods = ref([]); // 已获取的商品列表
const noMoreData = ref(false); // Indicates if there's no more data to load

// --- DOM References ---
const scrollContainer = ref(null); // Reference to the scrollable div

// --- Functions ---
const tabClick = (index) => {
  // Reset pagination state when tab changes
  currentType.value = tabs.value[index].name;
  currentPage.value = 1; // Reset to first page
  fetchedGoods.value = []; // Clear previous goods
  noMoreData.value = false; // Reset "no more data" flag
};

const fetchGoods = async (type, page, append = false) => {
  if (loadingGoods.value || noMoreData.value) return; // Prevent duplicate requests or if no more data

  loadingGoods.value = true;
  goodsError.value = null; // Clear previous errors
  let responseResult = null;

  try {
    if (type === "deal") {
      responseResult = await getAllDealProductList(page, pageSize);
    } else if (type === "hot") {
      // TODO: Implement API for 'hot' products
      // responseResult = await getHotProductList(page, pageSize);
      console.warn("Hot product API not implemented yet.");
      loadingGoods.value = false;
      noMoreData.value = true; // For now, assume no more data for unimplemented types
      return;
    } else if (type === "guess") {
      // TODO: Implement API for 'guess' products
      // responseResult = await getGuessProductList(page, pageSize);
      console.warn("Guess product API not implemented yet.");
      loadingGoods.value = false;
      noMoreData.value = true; // For now, assume no more data for unimplemented types
      return;
    } else {
      loadingGoods.value = false;
      noMoreData.value = true; // No recognized type
      return;
    }

    if (responseResult.status !== 200) {
      throw new Error(`HTTP error! status: ${responseResult.statusText}`);
    }

    const rrJson = responseResult.data;

    if (rrJson.code === 1) {
      const newRecords = rrJson.data.records || [];
      if (append) {
        fetchedGoods.value = [...fetchedGoods.value, ...newRecords]; // 第二查询时， 使用Append new data
      } else {
        fetchedGoods.value = newRecords; // 第一次查询 Replace data for initial load or tab change
      }

      // Check if there are no more pages
      if (newRecords.length < pageSize) {
        noMoreData.value = true;
      } else {
        noMoreData.value = false;
      }
    } else {
      goodsError.value = rrJson.msg || `Failed to fetch ${type} products`;
      if (!append) {
        fetchedGoods.value = []; // Clear only if not appending
      }
      noMoreData.value = true; // Assume no more data on error
    }
  } catch (e) {
    goodsError.value = "Network request failed: " + e.message;
    if (!append) {
      fetchedGoods.value = []; // Clear only if not appending
    }
    noMoreData.value = true; // Assume no more data on network error
    console.error(`Error fetching ${type} offers:`, e);
  } finally {
    loadingGoods.value = false;
  }
};
// handle scroll event
const handleScroll = () => {
  const container = scrollContainer.value || document.documentElement; // Fallback to documentElement for window scroll
  const isAtBottom =
    container.scrollTop + container.clientHeight >= container.scrollHeight - 50; // 50px buffer

  if (isAtBottom && !loadingGoods.value && !noMoreData.value) {
    currentPage.value++; // Increment page number
    fetchGoods(currentType.value, currentPage.value, true); // Fetch next page, appending data
  }
};

// --- Watchers ---
watch(
  currentType,
  (newType) => {
    fetchGoods(newType, 1, false); // Fetch first page when type changes
  },
  { immediate: true }
);

// --- Lifecycle Hooks ---
onMounted(async () => {
  try {
    // Load initial static data with error handling
    const promises = [
      getAllBannerList().catch(err => {
        console.warn('轮播图API失败:', err.message);
        return { data: { code: 0, data: [] } }; // 返回空数据
      }),
      getAllCategoryList().catch(err => {
        console.warn('分类API失败:', err.message);
        return { data: { code: 0, data: [] } }; // 返回空数据
      }),
      fetch("/tabs.json").catch(err => {
        console.warn('标签数据失败:', err.message);
        return { json: () => ({ data: [{ name: 'deal', title: '特价' }] }) }; // 返回默认数据
      })
    ];

    const [bannerRes, categoryRes, tabsRes] = await Promise.all(promises);

    // Process banner data
    const bannerJson = bannerRes.data;
    if (bannerJson.code === 1) {
      banners.value = bannerJson.data;
    }

    // Process category data
    const categoryJson = categoryRes.data;
    if (categoryJson.code === 1) {
      recommends.value = categoryJson.data;
    }

    // Process tabs data
    const tabsData = await tabsRes.json();
    tabs.value = tabsData.data;

    // Add scroll event listener to the window
    window.addEventListener("scroll", handleScroll);

    // 初始化购物车数据
    await shopStore.initializeCart();
  } catch (error) {
    console.error('页面初始化失败:', error);
    // 不显示错误提示，让页面正常显示空数据
  }
});

onUnmounted(() => {
  // Clean up scroll event listener when component is unmounted
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
/* Optional: Basic styling for loading/error messages */
.loading-indicator,
.error-message,
.no-more-data {
  text-align: center;
  padding: 20px;
  color: #666;
}
.error-message {
  color: red;
}

/* If you want a specific scrollable area instead of the whole window */
.scroll-container {
  /* max-height: calc(100vh - 100px); /* Example: adjust based on header/footer height */
  /* overflow-y: auto; */
}
</style>